import fetch from 'dva/fetch';
import { parseParam } from '@/utils/urlUtil';
import Cookies from 'js-cookie';

export default function request(url, options = {}, host = '') {
  //默认设置
  const defaultOptions = {
    method: 'GET',
    mode: 'cors',
  };

  const newOptions = { ...defaultOptions, ...options };
  newOptions.headers = {
    Accept: 'application/json',
    Authorization: Cookies.get('token') || '', //header里面的token
    ...newOptions.headers,
  };

  // 设置url
  url = parseParam(url, options.params);
  // 删除body
  if (newOptions.method == 'GET') delete newOptions.body;

  return fetch(host + url, newOptions)
    .then(async response => {
      var store = window.g_app._store;
      var status = response.status;
      var data = await response.json();

      //正常情况
      if (response.status >= 200 && response.status < 300) {
        if (data.code == 551000 || data.code == 551001 || data.code == 551002) {
          store.dispatch({ type: 'login/logout', payload: {} });
        }

        return data;
      }

      // 报错抛出错误
      if (status >= 400 || status >= 500) {
        const error = new Error();
        error.response = response;
        error.data = data;
        throw error;
      }
    })
    .catch(async e => {
      var status = 503;
      var msg = '链接服务器超时';
      return {
        code: status,
        msg: msg,
      };
    });
}
